package com.example.skillcinema.ui.screens.main

import android.app.Dialog
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.ImageButton
import androidx.appcompat.widget.AppCompatButton
import androidx.core.view.isVisible
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import com.bumptech.glide.Glide
import com.example.skillcinema.R
import com.example.skillcinema.adapters.DialogCollectionRecyclerViewAdapter
import com.example.skillcinema.databinding.FragmentCollectionDialogBinding
import com.example.skillcinema.db.displaymodels.DialogCollection
import com.example.skillcinema.db.localdb.tables.CollectionEntity
import com.example.skillcinema.ui.screens.main.viewmodels.DialogCollectionViewModel
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch

@AndroidEntryPoint
class CollectionDialogFragment : BottomSheetDialogFragment() {
    private var _binding: FragmentCollectionDialogBinding? = null
    private val binding: FragmentCollectionDialogBinding
        get() = _binding!!
    private val viewModel: DialogCollectionViewModel by viewModels<DialogCollectionViewModel>()

    private var filmId: Int = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            filmId = it.getInt(FILM_ID_ARG)
            viewModel.filmId = filmId
            viewModel.loadData()
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentCollectionDialogBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val adapter: DialogCollectionRecyclerViewAdapter =
            DialogCollectionRecyclerViewAdapter(
                { collection -> toggleCollection(collection) },
                { createCollection() })
        binding.collectionRecyclerView.adapter = adapter
        binding.closeButton.setOnClickListener {
            close()
        }
        with(binding) {
            lifecycleScope.run {
                launch {
                    viewModel.filmDataFlow.collect {
                        ratingTextView.text = it.rate.toString()
                        ratingTextView.isVisible = it.rate > 0.0f
                        filmNameTextView.text = it.name
                        filmGenreTextView.text = it.genre

                        Glide.with(filmImageView)
                            .load(it.imageUrl)
                            .placeholder(android.R.drawable.progress_indeterminate_horizontal)
                            .error(android.R.drawable.stat_notify_error)
                            .into(filmImageView)
                    }
                }
                launch {
                    viewModel.collectionsFlow.collect {
                        adapter.setData(it.toMutableList())
                    }
                }
            }
        }
    }

    private fun toggleCollection(collection: DialogCollection) {
        viewModel.toggleCollection(collection)
    }

    private fun createCollection() {
        val dialog = Dialog(requireContext())
        dialog.setContentView(R.layout.dialog_collection_create)
        val editTextView = dialog.findViewById<EditText>(R.id.nameEditTextView)
        val createButton = dialog.findViewById<AppCompatButton>(R.id.createButton)
        val closeButton = dialog.findViewById<ImageButton>(R.id.closeButton)

        createButton.setOnClickListener {
            if (editTextView.text.isNotBlank()) {
                viewModel.createCollection(editTextView.text.toString().trim())
            }
            dialog.dismiss()
        }
        closeButton.setOnClickListener { dialog.dismiss() }
        dialog.show()
    }

    private fun close() {
        dismiss()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    companion object {
        @JvmStatic
        fun newInstance(param1: Int) = CollectionDialogFragment().apply {
            arguments = Bundle().apply {
                putInt(FILM_ID_ARG, param1)
            }
        }

        const val FILM_ID_ARG = "film_id"
    }
}